#  Copyright (c) 2010
#  The Regents of the University of Michigan
#  All Rights Reserved

#  Permission is granted to use, copy, create derivative works, and
#  redistribute this software and such derivative works for any purpose,
#  so long as the name of the University of Michigan is not used in
#  any advertising or publicity pertaining to the use or distribution
#  of this software without specific, written prior authorization. If
#  the above copyright notice or any other identification of the
#  University of Michigan is included in any copy of any portion of
#  this software, then the disclaimer below must also be included.

#  This software is provided as is, without representation or warranty
#  of any kind either express or implied, including without limitation
#  the implied warranties of merchantability, fitness for a particular
#  purpose, or noninfringement.  The Regents of the University of
#  Michigan shall not be liable for any damages, including special,
#  indirect, incidental, or consequential damages, with respect to any
#  claim arising out of or in connection with the use of the software,
#  even if it has been or is hereafter advised of the possibility of
#  such damages.

from torrent_classifier import classify, torrentcat

import collections
import glob
import gzip
import sys

def make_out_file(category):
  return open('%s.out' % category, 'w')

if __name__ == '__main__':
  counts = collections.defaultdict(int)
  category_logs = {}
  for pat in sys.argv[1:]:
    for fyl in glob.iglob(pat):
      if fyl.endswith('.gz'):
        contents = gzip.open(fyl).read()
      else:
        contents = open(fyl).read()
      category = classify(contents)
      counts[category] += 1

      if category not in category_logs:
        category_logs[category] = make_out_file(category)
      category_logs[category].write('%s\t%s' % (fyl, category))
      torrentcat.cat(fyl, category_logs[category])
  results = counts.items()
  results.sort(key=lambda x: x[1])
  results.reverse()
  total = float(sum(x[1] for x in results))
  for (category, count) in results:
    print '%2.1f%% (%d)\t%s' % (count * 100 / total, count, category)
